from rest_framework.views import APIView
from rest_framework.response import Response
from user import models
from django.db.models import Q
from utils.jwttool import tool


class LoginView(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        query = Q(username=account) | Q(email=account) | Q(phone=account)
        info = models.User.objects.filter(query).first()
        if not info:
            return Response({'msg': '账号不存在', 'code': 400})
        if info.password == password:
            token = tool.get_token(info.id)
            return Response({"msg": "登录成功", "code": 200, "data": {"token": token, "userid": info.id}})
        else:
            return Response({'msg': '密码错误', 'code': 400})
